<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/5/31
 * Time: 15:20
 */

namespace app\api\controller\deliver\v1;


use app\api\model\Common;
use app\api\model\UserOrderClockIn;
use think\Controller;
use think\Request;
use app\api\model\AliPay;
use think\Db;
use app\api\model\Authority;
use think\Exception;

class ClockIn extends Controller
{
    protected $us;
    
    public function _initialize()
    {
        $this->us = Authority::check(1);
        
    }
    
    /**
     * 打卡
     */
    public function clockIn(UserOrderClockIn $clockIn, Common $common)
    {
        $data = Request::instance()->get();
        $time = time();
        db()->startTrans();
        $data['type']=23;
        $resource = isset($data['resource']) ? json_decode(trim($data['resource'], "'"), true) : null;
        try {
            if ($resource != null || is_array($resource)) {
                if(!empty($resource)){
                    if($this->us['work_clothes']==1){
                        $detectUrl=detectUrl($resource[0]['path']);
                        $detectUrl=json_decode($detectUrl,true);
                        if($detectUrl['status']=='success' &&(empty($detectUrl['detections']) || $detectUrl['detections'][0]['confidence'] <50))  {
                            r_date(null, 300,$detectUrl['message']);
                        }
                    }
                   
                }
                $listNode                 = $common->addResourceIds($resource);
                $add_data['resource_ids'] = implode(',', $listNode);
                
            } else {
                throw new Exception('请使用拍摄打卡');
            }
            $add_data['user_id']     = $this->us['user_id'];
            $add_data['clock_in_at'] = $time;
            $add_data['type']        = 23;
            $add_data['remark']      =$data['remark'];
            $add_data['order_id']      =isset($data['chooseOrderId'])?$data['chooseOrderId']:0;
            $add_data['lng']      =$data['lng'];
            $add_data['lat']      =$data['lat'];
            $add_data['address']      =$data['address'];
            $end               = strtotime(date('Y-m-d 17:59:59', time()));
            if($end<$add_data['clock_in_at']){
                $add_data['type']        = 24;
            }
            if ($data['type'] == 23) {
                $months = dayBetween(time());
                $result = $clockIn->field('type, order_id, clock_in_at, lng, lat, address')
                    ->where('user_id', $this->us['user_id'])
                    ->where('type', $clockIn::TYPE_CLOCK_OUT_STORE)
                    ->whereBetween('clock_in_at', [$months['first'], $months['last']])
                    ->where('status', $clockIn::STATUS_ON)->count();
                if ($result != 0) {
                    $add_data['type'] = $clockIn::TYPE_CLOCK_OUT_WORK;
                }
                
            }
            $clockIn->save($add_data);
            $common->MultimediaResources(empty($add_data['order_id'])?0:$add_data['order_id'],$this->us['user_id'],$resource,10);
            $response['clock_in_at'] = $add_data['clock_in_at'];
            $response['lng'] = $add_data['lng'];
            $response['lat'] = $add_data['lat'];
            $response['address'] = $add_data['address'];
            DB::commit();
            r_date(null,200);
        } catch (\Exception $e) {
            DB::rollBack();
            r_date(null,300, $e->getMessage());
        }
      
    }
    
    /**
     * 打卡记录列表
     */
    public function lists(UserOrderClockIn $clockIn)
    {
        $data  = Authority::param(['date']);
        $month = monthBetween($data['date']);
        $query = $clockIn->field("from_unixtime(clock_in_at, '%d') AS d, count(*) AS count");
        $query->where('user_id', $this->us['user_id']);
        $query->where(function ($query) {
            $query->whereNull('deleted_at')
                ->whereOr('deleted_at', 0);
        });
        $query->whereBetween('clock_in_at', [$month['first'], $month['last']]);
        $query->where('status', $clockIn::STATUS_ON);
        $query->order('clock_in_at', 'asc');
        $query->group('d');
        $result = $query->select();
        r_date($result);
    }
    
    /**
     * 打卡详情
     */
    public function detail(UserOrderClockIn $clockIn)
    {
        $data  = Authority::param(['date']);
        $day   = dayBetween($data['date']);
        $query = $clockIn->field('type,order_id,clock_in_at,lng,lat,address,resource_ids');
        $query->where('user_id', $this->us['user_id']);
        $query->where(function ($query) {
            $query->whereNull('deleted_at')
                ->whereOr('deleted_at', 0);
        });
        $query->whereBetween('clock_in_at', [$day['first'], $day['last']]);
        $query->where('status', $clockIn::STATUS_ON);
        $query->order('created_at', 'asc');
        $result        = $query->select();
        $groupedResult = [];
        foreach ($result as $item) {
            $orderId = $item['order_id'];
            if (!isset($groupedResult[$orderId])) {
                $groupedResult[$orderId] = [];
            }
            $groupedResult[$orderId][] = $item;
        }
        
        $dat=[];
        foreach ($groupedResult as $item) {
            $data['start']=null;
            $data['end']=null;
            foreach ($item as $value) {
                if (in_array($value['type'], [$clockIn::TYPE_CLOCK_IN, $clockIn::TYPE_CLOCK_IN_REFRESH])) {
                    $value['resource'] = $clockIn->resource($value['resource_ids']);
                    $data['start']     = $value;
                }
                if (in_array($value['type'], [$clockIn::TYPE_CLOCK_OUT, $clockIn::TYPE_CLOCK_OUT_REFRESH])) {
                    $value['resource'] = $clockIn->resource($value['resource_ids']);
                    $data['end']       = $value;
                }
                if (in_array($value['type'], [$clockIn::TYPE_CLOCK_OUT_STORE])) {
                    $value['resource'] = $clockIn->resource($value['resource_ids']);
                    $data['start']     = $value;
                }
                if (in_array($value['type'], [$clockIn::TYPE_CLOCK_OUT_WORK])) {
                    $value['resource'] = $clockIn->resource($value['resource_ids']);
                    $data['end']       = $value;
                }
            }
            $dat[]=[
                'start' => isset($data['start']) ? $data['start'] : (object)null,
                'end' => isset($data['end']) ? $data['end'] : (object)null
            ];
        
        }
       
        r_date($dat);
    }
    
    /*
     * 打开规则
     */
    public function clockInDistance(UserOrderClockIn $clockIn)
    {
        $data = Authority::param(['lat', 'lng']);
        if (empty($data['lat']) && empty($data['lng'])) {
            return apiResponse(300, null, "经纬度错误");
        }
        $request         = Request::instance()->post();
        $theSameDay        = date('Y-m-d', time());
        $theSameDayMorning = strtotime($theSameDay);
        $theSameDayNight   = strtotime($theSameDay) + 866400;
        $ClockInTime       = time();
        $start             = strtotime(date('Y-m-d 09:00:00', time()));
        $end               = strtotime(date('Y-m-d 17:59:59', time()));
        $clock_in_distance = Db::connect(config('database.db2'))->table('config')->where('name', 'clock_in_distance')->find();
        $distance          = json_decode($clock_in_distance['content'], true);
        $lat               = '';
        $lng               = '';
        $value             = 0;
        $content           = '';
        if (isset($request['order_id']) && !empty($request['order_id'])) {
            $order = Db::connect(config('database.db2'))->table('order')->where('order_id', $request['order_id'])->find();
            $lat   = $order['lat'];
            $lng   = $order['lng'];
            foreach ($distance as $l) {
                if ($l['type'] == 1) {
                    $value = $l['value'] * 1000;
                }
            }
            $app_user_order_clock_in = $clockIn->where('order_id', $request['order_id'])->whereBetween('clock_in_at', [$theSameDayMorning, $theSameDayNight])->whereIn('type', [23, 24])->where('user_id', $this->us['user_id'])->count();
            
        } else {
            $app_user_order_clock_in = $clockIn->whereBetween('clock_in_at', [$theSameDayMorning, $theSameDayNight])->whereIn('type', [23, 24])->where('user_id', $this->us['user_id'])->count();
            $store                   = Db::connect(config('database.db2'))->table('store')->where('store_id', $this->us['store_id'])->find();
            $lat                     = $store['lat'];
            $lng                     = $store['lng'];
            foreach ($distance as $l) {
                if ($l['type'] == 2) {
                    $value = $l['value'] * 1000;
                }
            }
            
        }
        $value=200;
        
        if (!empty($lat) && !empty($lng) && !empty($data['lat']) && !empty($data['lng'])) {
            
            $Difference = getDistance($lat, $lng, $data['lat'], $data['lng']);
            //1.在打卡距离超过工地或店铺X公里时（X在城市库config里配置），先弹出提示框，提示“超过X公里内打卡的范围，请填写说明”
            if ($Difference > $value && $app_user_order_clock_in == 0 && $start > $ClockInTime) {
                $content = ['title' => '*超过' . $value . '米内打卡的范围，请填写说明;', 'content' => "*超出店铺或工地距离，需要备注原因，备注后才算打卡成功。"];
            }
            //3.距离在范围内，时间在9点以后，18点以前的首次打卡，提示“迟到打卡，请填写说明”
            if ($Difference <= $value && $start < $ClockInTime && $ClockInTime < $end && $app_user_order_clock_in == 0) {
                $content = ['title' => "*迟到打卡，请填写说明(打卡范围内);", 'content' => "*当前定位在打卡范围内，但已超出上班打卡时间，请填写迟到原因。"];
            }
            //4.距离在范围内，时间在9点以后，18点以前的二次打卡，提示“早退打卡，请填写说明”
            if ($Difference <= $value && $end > $ClockInTime && $app_user_order_clock_in >= 1) {
                $content = ['title' => '*早退打卡，请填写说明(打卡范围内);', 'content' => "*当前定位在打卡范围内，但未到达下班打卡时间，请填写原因。"];;
            }
            //5.距离超过范围，时间在9点以后，18点以前的首次打卡，提示“迟到打卡且超范围，请填写说明”
            if ($Difference > $value && $start < $ClockInTime && $app_user_order_clock_in == 0) {
                $content = ['title' => '*迟到打卡，请填写说明(未在打卡范围内);', 'content' => "*当前定位未在打卡范围内，且已超出上班打卡时间请填写原因。"];;
            }
            //6.距离超过范围，时间在9点以后，18点以前的二次打卡，提示“早退打卡且超范围，请填写说明”，
            if ($Difference > $value && $end > $ClockInTime && $app_user_order_clock_in >= 1) {
                $content = ['title' => '*早退打卡，请填写说明(未在打卡范围内);', 'content' => "*当前定位未在打卡范围内，且未到达下班打卡时间，请填写原因。"];;
            }
            //7.距离超过范围，时间在9点以后，18点以后的二次打卡，提示“早退打卡且超范围，请填写说明”，
            if ($Difference > $value && $end < $ClockInTime && $app_user_order_clock_in >= 1) {
                $content = ['title' => '*超过' . $value . '米内打卡的范围，请填写说明;', 'content' => "*超出店铺或工地距离，需要备注原因，备注后才算打卡成功。"];
            }
        }
        if (empty($lat) && empty($lng) || (empty($lat) || empty($lng))) {
            //6.，时间在9点以后，18点以前的二次打卡，提示“早退打卡且超范围，请填写说明”，
            if ($end > $ClockInTime && $app_user_order_clock_in >= 1) {
                $content = ['title' => '早退打卡，请填写说明(未知打卡范围)', 'content' => "当前定位未知，且未到达下班打卡时间，请填写原因"];;
            }
            //5.时间在9点以后，18点以前的首次打卡，提示“迟到打卡且超范围，请填写说明”
            if ($start < $ClockInTime && $app_user_order_clock_in == 0) {
                $content = ['title' => '迟到打卡，请填写说明(未知打卡范围)', 'content' => "当前定位未知，且已超出上班打卡时间请填写原因，"];;
            }
        }
        if (empty($content)) {
            r_date(['content' => null, 'code' => 200]);
        }
        r_date(['content' => $content, 'code' => 300, 'explanatoryNote' => "注:提交后自动进入拍照流程，提交拍照后，完成打卡"]);
    }
    
}